import json
import jsonpath

book_json = """
{
  "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-394-19394-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}
"""

# 将JSON格式的字符串转换为python对象
books = json.loads(book_json)
print(type(books))
print(books)

# 选取bicycle对象中字段color的值
json_expression = "$.store.bicycle.color"
result = jsonpath.jsonpath(books, json_expression)      # 返回列表
print(result)

# 选取book列表中包含的所有对象
json_expression = "$.store.book[*]"
result = jsonpath.jsonpath(books, json_expression)
print(result)

# 选取book列表的第一个对象
json_expression = "$.store.book[0]"
result = jsonpath.jsonpath(books, json_expression)
print(result)

# 选取book列表中所有对象的属性title值
json_expression = "$.store.book[*].title"
result = jsonpath.jsonpath(books, json_expression)
print(result)

# 选取book列表中属性category的值为fiction的所有对象
json_expression = "$.store.book[?(@.category=='fiction')"       # 过滤操作
result = jsonpath.jsonpath(books, json_expression)
print(result)

# 选取book列表中所有price的值小于10的对象
json_expression = "$.store.book[?(@.price<10)]"
result = jsonpath.jsonpath(books, json_expression)
print(result)

# 选取book列表中所有包含isbn的对象
json_expression = "$.store.book[?(@.isbn)]"
result = jsonpath.jsonpath(books, json_expression)
print(result)
